package fr.afcepf.ticketing.service;

import java.util.ArrayList;
import java.util.List;


import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.ejb.Stateful;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import fr.afcepf.ticketing.domain.Ticket;

@Stateful
public class CartServiceBean implements CartService {

	@PersistenceContext
	private EntityManager entityManager;
	
	private List<CartTicket> cartTickets;

	@PostConstruct
	public void initialize() {
		cartTickets = new ArrayList<CartTicket>();
	}

	@PreDestroy
	public void clear() {
		cartTickets = null;
	}

	public void addTicket(Ticket ticket) {
		boolean ticketOK = false;
		for (CartTicket cartTicket : cartTickets) {
			if (cartTicket.getTicket().equals(ticket)) {
				cartTicket.setQuantity(cartTicket.getQuantity() + 1);
				ticketOK = true;
			}
		}
		if (!ticketOK)
			cartTickets.add(new CartTicket(ticket, 1));
	}

	public void removeTicket(Ticket ticket) {
		for (CartTicket cartTicket : cartTickets) {
			if (cartTicket.getTicket().equals(ticket)) {
				cartTickets.remove(cartTicket);
				return;
			}
		}
	}
	

	public Float getTotal() {
		if (cartTickets == null || cartTickets.isEmpty())
			return 0f;

		Float total = 0f;

		for (CartTicket cartTicket : cartTickets) {
			total += (cartTicket.getTicketsPrice());
		}
		return total;
	}

	public void empty() {
		cartTickets.clear();
	}

	public List<CartTicket> getCartTickets() {
		return cartTickets;
	}

}
